Introduction to Apache Tomcat and Servlet Containers
Course: Advanced Java Training
Topic: Introduction to Apache Tomcat and Servlet Containers
Course Link: Advanced Java Training Course
Demo Link: Register for a Free Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction
Apache Tomcat is a widely used open-source server that provides a runtime environment for Java web applications. It implements key Jakarta EE web specifications, including Jakarta Servlet and Jakarta Server Pages (JSP). Developers use Tomcat to deploy, execute, test, and manage Java-based web applications.
A servlet container is the component responsible for managing the lifecycle of servlets and handling communication between web clients and Java web components. Tomcat includes a servlet container, so it can receive HTTP requests, invoke the appropriate servlet, and return HTTP responses.
Tomcat is commonly used for web applications built with Servlets, JSP, and related technologies. It is not a full Jakarta EE application server and does not provide every enterprise service defined by the broader Jakarta EE platform.
2. Learning Objectives
- Understand Apache Tomcat and its purpose.
- Learn what a servlet container is and why it is required.
- Understand the relationship between Tomcat, Servlets, and HTTP.
- Explore Tomcat's architecture and important components.
- Learn the servlet lifecycle and request-processing flow.
- Install, configure, start, and stop Tomcat.
- Deploy a Java web application using a WAR file.
- Understand common configuration files, ports, and troubleshooting techniques.
3. What Is Apache Tomcat?
Apache Tomcat is an open-source implementation of selected Jakarta EE web specifications maintained by the Apache Software Foundation. It provides the infrastructure required to run Java web components such as Servlets and JSP pages.
When a user visits a Java web application, Tomcat accepts the HTTP request, identifies the application and resource, and routes the request to the appropriate web component. The component processes the request and generates a response that Tomcat sends back to the client.
Key Features of Apache Tomcat
- Servlet support: Executes Java servlet components.
- JSP support: Processes JSP pages by translating and compiling them into servlets as needed.
- HTTP request handling: Accepts HTTP requests and sends responses.
- Web application deployment: Supports deploying applications using directories or WAR archives.
- Configuration: Provides configuration files for connectors, hosts, contexts, and other server settings.
- Security: Supports access restrictions, TLS configuration, authentication integration, and secure deployment practices.
- Logging: Provides logs that help developers monitor application behavior and investigate errors.
- Development support: Can run locally for development and testing, as well as in suitable production environments.
4. What Is a Servlet Container?
A servlet container is a runtime environment that manages Java servlets and implements the Servlet specification. It acts as a bridge between the web server's request-handling infrastructure and the Java code that implements web application behavior.
When a request reaches the container, it determines which servlet should handle it, prepares the request and response objects, invokes the servlet, and manages the servlet's lifecycle.
Responsibilities of a Servlet Container
- Loading servlet classes and creating servlet instances.
- Calling lifecycle methods such as
init(), service(), and destroy() at the appropriate times.
- Mapping incoming URLs to servlet components.
- Creating
HttpServletRequest and HttpServletResponse objects.
- Managing sessions and cookies through the web APIs.
- Applying configured filters and security constraints.
- Managing servlet configuration and application deployment.
- Providing error handling and integration with logging mechanisms.
5. Apache Tomcat vs. Servlet Container
A servlet container is a type of software component; Apache Tomcat is a concrete implementation that includes one. The terms are related but are not interchangeable in every context.
| Aspect |
Servlet Container |
Apache Tomcat |
| Meaning |
A runtime that implements servlet-related web specifications. |
An open-source server that provides a servlet container and related web capabilities. |
| Purpose |
Manages servlet execution and lifecycle. |
Runs Java web applications and accepts HTTP traffic. |
| Examples |
General category of software. |
Apache Tomcat is a specific implementation. |
| Deployment |
Depends on the particular container. |
Supports web application directories and WAR archives. |
| Technologies |
Depends on specifications implemented. |
Includes Servlet and JSP support, along with related web features. |
6. How Tomcat Works
Tomcat receives requests from clients, such as web browsers or API clients, and forwards them through its request-processing components to the appropriate web application.
Client / Web Browser
|
| HTTP Request
v
Tomcat Connector
|
v
Engine / Virtual Host / Web Application Context
|
v
URL Mapping and Servlet Container
|
v
Servlet / Controller
|
v
Business Logic / Data Access
|
v
HTTP Response
|
v
Client / Web Browser
Request Processing Steps
- Client sends a request: A browser requests a URL such as
http://localhost:8080/HelloApp/hello.
- Connector accepts the request: Tomcat listens on the configured connector port, commonly port 8080 for HTTP in a default development setup.
- Tomcat identifies the application: The request is routed according to its host, context path, and URL mapping.
- Filters are applied: Any matching filters can process the request before and after the target servlet.
- Servlet executes: The container invokes the servlet's request-processing method.
- Response is generated: The servlet sets the response status, headers, and body.
- Response is returned: Tomcat sends the HTTP response to the client.
7. Important Components of Tomcat Architecture
7.1 Server
The top-level Server represents the Tomcat server instance. It coordinates the lifecycle of the service or services configured within it.
7.2 Service
A Service groups a connector with an engine. It connects the network-facing request listener to the component that processes requests.
7.3 Connector
A connector accepts network connections and converts incoming requests into a form Tomcat can process. A common development configuration uses an HTTP connector on port 8080. Secure HTTPS connectors require appropriate TLS configuration.
7.4 Engine
The engine processes requests delivered by a service and selects the appropriate virtual host for the request.
7.5 Host
A host represents a virtual host within Tomcat. It can be configured to serve one or more web applications under a particular host name.
7.6 Context
A context represents a deployed web application. It defines the application's configuration and provides the environment in which its web components operate.
7.7 Servlet Container
The servlet container manages servlet instances, lifecycle methods, URL mappings, request and response objects, sessions, and related web application behavior.
8. Apache Tomcat Directory Structure
A standard Tomcat installation contains directories and files that support configuration, deployment, runtime data, and diagnostics. Exact contents can vary by version and installation method.
| Directory or File |
Purpose |
bin/ |
Contains startup, shutdown, and other utility scripts. |
conf/ |
Contains server configuration files. |
conf/server.xml |
Configures the server, services, connectors, engines, and hosts. |
conf/web.xml |
Provides default web application configuration for the container. |
webapps/ |
Common deployment location for web applications and WAR files. |
logs/ |
Stores server and application-related logs, depending on logging configuration. |
lib/ |
Contains libraries used by the Tomcat server. |
work/ |
Stores generated working files, such as compiled JSP artifacts. |
temp/ |
Provides temporary storage for runtime operations. |
9. Installing and Starting Apache Tomcat
Before installing Tomcat, check the Java requirements for the particular Tomcat release. Different major versions support different Java versions and Jakarta namespace levels.
Step 1: Check Java
Open a terminal or command prompt and run:
java -version
If Java is missing or the version is incompatible, install a supported JDK and configure JAVA_HOME as required by your operating system and Tomcat version.
Step 2: Download Tomcat
Download a suitable release from the official Apache Tomcat website. Choose the version compatible with your application's Java version and API namespace.
Official Apache Tomcat Website
Step 3: Extract the Distribution
Extract the downloaded archive to a directory, for example:
C:\apache-tomcat
/opt/tomcat
These are example locations only; use a path appropriate for your operating system.
Step 4: Start Tomcat
On Windows, open the Tomcat bin directory and run:
startup.bat
On Linux or macOS, run:
./startup.sh
Run the script from the Tomcat bin directory. On Unix-like systems, ensure the script has execute permission if needed.
Step 5: Verify the Installation
Open the following address in a browser when Tomcat is running with its default HTTP connector:
http://localhost:8080/
If the server is configured correctly and the default root application is available, the Tomcat welcome page may appear. If it does not, check the startup output, logs, port configuration, and firewall settings.
Step 6: Stop Tomcat
On Windows, run:
shutdown.bat
On Linux or macOS, run:
./shutdown.sh
For service-based installations, use the relevant operating-system service management commands instead.
10. Creating a Simple Servlet
A servlet is a Java class that runs inside a servlet container. The following example uses the modern jakarta.servlet namespace, which is appropriate for compatible Tomcat releases such as Tomcat 10 and later.
HelloServlet.java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello from Apache Tomcat!</h1>");
out.println("<p>Your servlet is running successfully.</p>");
out.println("</body>");
out.println("</html>");
}
}
}
Understanding the Code
@WebServlet("/hello") maps the servlet to the /hello URL pattern.
HttpServlet provides HTTP-specific servlet behavior.
doGet() handles HTTP GET requests.
HttpServletRequest provides access to request data.
HttpServletResponse is used to configure and write the response.
setContentType() declares the response content type and character encoding.
Important: For Tomcat 9 and earlier, servlet code generally uses the older javax.servlet namespace. Tomcat 10 and later use jakarta.servlet. Choose the API imports and dependency versions that match your container; the two namespaces are not directly interchangeable.
11. Deploying a Web Application
Tomcat can deploy a web application from an expanded directory or a WAR (Web Application Archive) file. A WAR file packages the application's classes, libraries, resources, and deployment descriptors in a standard archive structure.
Typical Web Application Structure
HelloApp/
├── index.html
├── WEB-INF/
│ ├── web.xml
│ ├── classes/
│ │ └── com/example/HelloServlet.class
│ └── lib/
│ └── application-library.jar
The WEB-INF directory contains server-side application resources. Files within it are not served directly to the browser as ordinary public web files.
Deployment Steps
- Compile the servlet against the Servlet API version supported by the target Tomcat release.
- Arrange compiled classes and application resources in the appropriate web application structure.
- Package the application as a WAR file if required.
- Copy the WAR file or expanded application directory into Tomcat's configured application base, commonly
webapps/.
- Start or reload the application according to the deployment setup.
- Visit the application's context path and servlet mapping in the browser.
For an application named HelloApp with a servlet mapped to /hello, the URL commonly looks like this:
http://localhost:8080/HelloApp/hello
The context path may differ if the application is deployed or configured under a different name.
12. The Servlet Lifecycle in Tomcat
The servlet container manages the lifecycle of each servlet. Understanding the lifecycle helps developers know where to initialize resources and how to release them safely.
Lifecycle Methods
- Loading and instantiation: The container loads the servlet class and creates an instance when required.
init(): Called to initialize the servlet before it handles requests.
service(): Called to process incoming requests. In HttpServlet, this method dispatches requests to methods such as doGet() and doPost().
destroy(): Called when the container removes the servlet from service, giving it an opportunity to release resources.
A servlet instance may handle multiple requests concurrently. Avoid storing request-specific mutable information in servlet instance fields. Use local variables for request-specific data and apply suitable synchronization or concurrency-safe designs when shared state is necessary.
13. Servlet Mapping and URL Patterns
Servlet mapping determines which servlet should process a particular URL. Mapping can be declared with annotations or in a deployment descriptor.
Annotation Example
@WebServlet("/products")
public class ProductServlet extends HttpServlet {
// Request-handling methods
}
A request to /products under the application's context path can be routed to this servlet.
Mapping in web.xml
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
version="6.0">
<servlet>
<servlet-name>ProductServlet</servlet-name>
<servlet-class>com.example.ProductServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProductServlet</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
</web-app>
The descriptor's namespace and version must match the Servlet API level supported by the selected container.
14. Tomcat Configuration Files
14.1 server.xml
The server.xml file configures the Tomcat server architecture, including services, connectors, engines, and hosts. For example, the connector configuration determines which port accepts HTTP traffic.
Illustrative connector configuration:
<Connector port="8080"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
This snippet is an example of a connector declaration, not a complete server configuration. Preserve the structure and required elements of the existing configuration when making changes.
14.2 web.xml
The web.xml deployment descriptor can define servlet mappings, filters, listeners, session settings, welcome files, and security constraints. Many settings can also be configured through annotations or other application-specific configuration mechanisms.
14.3 context.xml
Context configuration controls aspects of a web application's runtime environment. Depending on the setup, context configuration can be defined globally, per host, or for an individual application. Be careful with resource definitions and environment-specific settings.
15. Tomcat and Full Jakarta EE Application Servers
Tomcat focuses on web application technologies. A full Jakarta EE application server provides a broader set of enterprise APIs and services, depending on its supported platform profile and version.
| Feature |
Apache Tomcat |
Full Jakarta EE Application Server |
| Servlets |
Supported |
Supported |
| JSP |
Supported in compatible releases |
Supported according to platform level |
| JPA provider and enterprise persistence integration |
Must be configured or supplied separately as needed |
Often provided through server-managed integration |
| Jakarta Enterprise Beans |
Not provided as a full built-in EJB container |
Available in servers that implement the relevant specifications |
| Jakarta Messaging |
Not a complete built-in Jakarta Messaging platform |
May be provided, depending on the server and profile |
| Typical use |
Servlet-based web apps, APIs, and web applications |
Applications needing a broader range of enterprise services |
The exact feature set depends on the Tomcat release, additional libraries, and the application server's supported Jakarta EE profile. Do not assume that installing Tomcat automatically provides every Jakarta EE service.
16. Common Tomcat Ports
| Port |
Typical Purpose |
Important Note |
| 8080 |
HTTP connector |
A common default for local development; configurable. |
| 8443 |
HTTPS connector |
Requires suitable TLS configuration and certificates. |
| 8005 |
Shutdown port in some configurations |
May be disabled, changed, or absent in a customized setup. |
| 8009 |
AJP connector in some configurations |
Not necessarily enabled; expose only when required and secured. |
These are conventional examples, not mandatory ports. Always inspect the active configuration before assuming a port is available or enabled.
17. Tomcat Logging and Monitoring
Logs provide information about server startup, deployment, application failures, and runtime warnings. When an application fails, checking the logs is often the fastest way to identify the underlying cause.
- Startup logs: Show whether Tomcat initialized successfully.
- Application logs: Record messages generated by application code and its logging framework.
- Access logs: Can record incoming requests, response status codes, and request-processing information when configured.
- Exception stack traces: Help locate Java errors and the code path that caused them.
Tomcat commonly writes logs to its configured log directory, often logs/. Exact filenames and destinations depend on the logging configuration and installation method.
18. Common Tomcat Problems and Solutions
| Problem |
Possible Cause |
Solution |
| Port already in use |
Another process is listening on the configured port. |
Identify the process, stop it if appropriate, or configure Tomcat to use another available port. |
| Tomcat fails to start |
Invalid configuration, incompatible Java version, or missing permissions. |
Review startup output and logs; validate the configuration and Java environment. |
| HTTP 404 Not Found |
Incorrect context path, missing resource, or unmatched servlet mapping. |
Verify the deployed application name, URL pattern, and resource path. |
| HTTP 500 Internal Server Error |
Unhandled exception or application configuration issue. |
Inspect stack traces and fix the underlying code or configuration error. |
| ClassNotFoundException |
Required application class or library is unavailable. |
Check the compiled classes and dependency packaging. |
| NoClassDefFoundError |
A required class cannot be loaded at runtime. |
Check dependency versions, classpath, and packaging. |
| Servlet API compilation error |
Incorrect API dependency or namespace mismatch. |
Match the Servlet API dependency to the target Tomcat version and use the correct javax or jakarta imports. |
| Application not deployed |
Invalid WAR structure, failed deployment, or configuration error. |
Inspect deployment logs and verify the WAR archive structure. |
| Changes are not visible |
Application was not recompiled or redeployed, or a cache is involved. |
Rebuild and redeploy the application, then inspect the active deployment. |
19. Security Best Practices
- Use a supported Tomcat release and apply relevant security updates.
- Use a Java version supported by the selected Tomcat release.
- Remove sample applications and unnecessary administrative applications from production installations.
- Protect management interfaces and restrict administrative access.
- Do not expose shutdown or AJP connectors to untrusted networks.
- Use HTTPS with correctly configured TLS when protecting traffic in transit.
- Run Tomcat with an operating-system account that has only the permissions it needs.
- Store secrets outside publicly accessible application resources and avoid committing them to source control.
- Validate user input and use parameterized database queries to reduce injection risks.
- Keep error responses from revealing stack traces, credentials, or internal implementation details to end users.
- Review access controls, logging, session configuration, and deployment permissions regularly.
20. Performance and Deployment Best Practices
- Configure JVM memory based on application requirements and measured usage.
- Use connection pooling when an application repeatedly accesses a database.
- Avoid expensive operations inside synchronized sections and avoid blocking work unnecessarily.
- Use appropriate timeouts for network and database operations.
- Monitor CPU, memory, thread usage, response times, and error rates.
- Load-test applications under realistic request volumes before production deployment.
- Use a reverse proxy or load balancer when the architecture requires it.
- Design sessions and application state carefully when running multiple application instances.
- Keep application dependencies organized and avoid placing unnecessary libraries in Tomcat's global
lib/ directory.
21. Mini Project: Deploy a Hello Servlet on Tomcat
Project Objective: Create a basic Java web application that displays a greeting when a user opens a URL in a browser.
Project Requirements
- Install a compatible JDK and Apache Tomcat release.
- Create a Java web application named
HelloApp.
- Implement a servlet mapped to
/hello.
- Return an HTML response from the servlet.
- Package and deploy the application.
- Verify that the endpoint works in a browser.
Expected Result
After successful deployment, open:
http://localhost:8080/HelloApp/hello
The browser should display a heading similar to “Hello from Apache Tomcat!” if the context path and servlet mapping match the example.
Project Extension Tasks
- Add a second servlet mapped to
/about.
- Read a query parameter such as
name from the request.
- Return a personalized greeting using safely encoded output.
- Add a filter to log request information without recording sensitive data.
- Configure a custom error page and test error handling.
- Package the application as a WAR and redeploy it.
22. Interview Questions and Answers
Q1. What is Apache Tomcat?
Apache Tomcat is an open-source server that provides a servlet container and supports Java web technologies such as Servlets and JSP.
Q2. What is a servlet container?
A servlet container is a runtime environment that manages servlet lifecycle, URL mapping, request and response objects, sessions, and related web application behavior.
Q3. Is Tomcat a web server or an application server?
Tomcat can act as an HTTP server for Java web applications and includes a servlet container. It is commonly described as a web server or servlet container, rather than a full Jakarta EE application server.
Q4. What is the difference between Tomcat and a servlet?
Tomcat is the runtime that hosts and manages web components. A servlet is a Java class that handles requests within that runtime.
Q5. What is a WAR file?
A WAR file is a Web Application Archive that packages a Java web application and its resources for deployment to a compatible servlet container.
Q6. What is the purpose of server.xml?
The server.xml file configures server-level components such as services, connectors, engines, and hosts.
Q7. What is the purpose of web.xml?
The web.xml deployment descriptor can configure servlets, mappings, filters, listeners, session settings, and security constraints for a web application.
Q8. What is the servlet lifecycle?
The container manages servlet loading and instantiation, initialization through init(), request handling through service(), and cleanup through destroy().
Q9. Why is port 8080 commonly used?
Port 8080 is a conventional default HTTP connector port in many Tomcat development configurations. Administrators can change it to suit their environment.
Q10. What is the difference between Tomcat 9 and Tomcat 10 or later regarding API packages?
Tomcat 9 uses Java EE-era APIs with the javax.servlet namespace. Tomcat 10 and later use Jakarta APIs with the jakarta.servlet namespace, so applications may require source or dependency changes when migrating.
Q11. How do you troubleshoot a 404 error?
Verify the context path, deployment status, resource location, servlet URL mapping, and deployment logs.
Q12. Can Tomcat run every Jakarta EE technology?
No. Tomcat implements selected web specifications. Applications that require additional enterprise services may need extra libraries or a full Jakarta EE application server.
23. Practical Exercises
- Install Tomcat and verify its welcome page.
- Create a servlet that handles a GET request.
- Map a servlet using
@WebServlet.
- Deploy an application using a WAR file.
- Change the HTTP connector port and verify the new URL.
- Cause a deliberate mapping error and diagnose the resulting 404 response.
- Inspect logs after a servlet throws an exception.
- Compare the package imports required by Tomcat 9 and Tomcat 10 or later.
24. Quick Revision Checklist
- Apache Tomcat is an open-source runtime for Java web applications.
- A servlet container manages servlet execution and lifecycle.
- Tomcat routes requests through connectors and server components to web applications.
- Common architecture components include Server, Service, Connector, Engine, Host, and Context.
- Port 8080 is a common development HTTP port, but configuration can vary.
- WAR files are a standard way to package Java web applications.
server.xml configures server-level components; web.xml can configure web application behavior.
- Tomcat 9 uses the
javax.servlet namespace; Tomcat 10 and later use jakarta.servlet.
- Logs are essential for diagnosing startup, deployment, and application errors.
- Production deployments should use supported versions, secure configuration, monitoring, and appropriate access controls.
25. Official Learning Resources
26. Conclusion
Apache Tomcat is an important component of Java web development because it provides a servlet container that runs web applications and manages servlet execution. Understanding its architecture, configuration, deployment process, request lifecycle, and troubleshooting techniques helps developers build and maintain reliable Java web applications.
For Advanced Java learners, practicing servlet development and deploying applications on Tomcat builds a strong foundation for working with enterprise web applications, REST APIs, filters, sessions, and related server-side technologies.